#include <stdio.h>
#include <stdlib.h>

// 双向链表，初始化时只有两个节点：head / tail，这两个节点不存储数据，仅占位
// 双向循环链表，初始化时只有一个节点，head，前向节点及后向节点均指向自己

typedef int data_t;

typedef struct dblink {
    int data;
    struct dblink *front;
    struct dblink *next; 
} dblink_t;

dblink_t * create_list() {
    dblink_t *head;
    dblink_t *tail;
    head = malloc(sizeof(dblink_t));
    tail = malloc(sizeof(dblink_t));
    head->front = NULL;
    head->next = tail;

    tail->front = head;
    tail->next = NULL;
    return head;
}

int ins_head_dblink(dblink_t *head, const data_t *data) {
    dblink_t *newnode;
    newnode = malloc(sizeof(dblink_t));

    newnode->data = *data;
    newnode->front = head;
    newnode->next = head->next;

    head->next->front = newnode;  //newnode->next->front = newnode;
    head->next = newnode;         //newnode->front->next = newnode;
    return 0;
}

int ins_tail_dblink(dblink_t *tail, const data_t *data) {
    dblink_t *newnode;

    newnode = malloc(sizeof(dblink_t));
    newnode->data = *data;
    newnode->next = tail;
    newnode->front = tail->front;

    tail->front->next = newnode;
    tail->front = newnode;
    return 0;
}

int print_list(dblink_t *head) {
    dblink_t *node;
    node = head->next;
    printf("链表数据为：\n");
    while(NULL != node->next) {
        printf("%d ", node->data);
        node = node->next;
    }
}

int main(int argc, const char *argv[])
{
    int tmp;
    dblink_t *head, *tail;
    head = create_list();
    tail = head->next;
    int i;
    for(i = 0; i < 10; i++) {
        tmp = 100 - i;
        ins_head_dblink(head, &tmp);
        tmp = 100 + i;
        ins_tail_dblink(tail, &tmp);
    }
    print_list(head);
    return 0;
}

